package labox.innovation.gameserver.network.clientpackets;

import labox.innovation.gameserver.model.L2Party;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;
import labox.innovation.gameserver.network.SystemMessageId;
import labox.innovation.gameserver.network.serverpackets.SystemMessage;

/**
 * @author ljsh
 * @date 2010-4-7
 * @version 1.0
 * @description 响应邀请入队请求
 */
public final class RequestAnswerJoinParty extends L2GameClientPacket {

	private static final String _C__2A_REQUESTANSWERPARTY = "[C] 2A RequestAnswerJoinParty";

	private int _response;

	private int _type;// 0为加入请求方队伍，1为将请求方加入己方队伍
	private static final int TEAM = 0;
	private static final int BYTEAM = 1;

	@Override
	protected void readImpl() {
		_type = readByte();
		_response = readByte();
	}

	@Override
	protected void runImpl() {
		FuzePcInstance player = getClient().getActiveChar();
		FuzePcInstance requestor = player.getActiveRequester();
		if (requestor == null || player == null)
			return;
		L2Party party = requestor.getParty();
		if (_type == TEAM) {
			if (_response == 1) {
				if (party != null)// Update by rocknow-Start
				{
					if (party.getMemberCount() >= L2Party.PARTY_MEMBER_LIMIT)// 队伍最多5个人
					{
						player.sendPacket(new SystemMessage(SystemMessageId.PARTY_FULL));
						return;
					}
				} else {
					party = new L2Party(requestor);
					requestor.setParty(party);
				}
				if(!party.isLeader(requestor))//如果请求者的队伍的队长不是请求者，则直接返回
				{
					return;
				}
				player.joinParty(party);
			} else {
				requestor.sendPacket(new SystemMessage(SystemMessageId.INVATATION_HAS_BE_REFUSED));// 拒绝你的邀请（系统消息）
			}
			
		}
		if (_type == BYTEAM) {
			if (_response == 1) {
				if (party != null) {
					player.sendPacket(new SystemMessage(SystemMessageId.C1_IS_ALREADY_IN_PARTY));// 对方已在队伍中
					return;
				}
				if(!player.isInParty()){
					player.sendPacket(new SystemMessage(SystemMessageId.YOUR_PARTY_HAS_BEEN_DISBANDED));
					return;
				}
				if (player.getParty().getMemberCount() < L2Party.PARTY_MEMBER_LIMIT) {
					requestor.joinParty(player.getParty());
				}
			} else {
				requestor.sendPacket(new SystemMessage(SystemMessageId.INVATATION_HAS_BE_REFUSED));// 拒绝你的邀请（系统消息）
			}
		}
		player.setActiveRequester(null);//响应请求后把请求者设置为空
	}

	@Override
	public String getType() {
		return _C__2A_REQUESTANSWERPARTY;
	}
}
